<template>
  <div>
    <van-nav-bar title="宝典列表" class="van_bar" />
    <div v-if="id">
      <van-search
        v-model="value"
        placeholder="请输入搜索关键词"
        disabled
        @click="toSearch"
        style="margin-top:45px"
      />
      <div class="content" ref="content">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <van-cell
              :class="[readArr.includes(item.id)?'read':'']"
              is-link
              icon="label-o"
              v-for="(item,index) in list"
              :key="index"
              :to="`/detail/${item.id}`"
              :title="item.title"
            />
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <div class="content" v-else>
      <van-button style="margin: 0 42%;" plain type="info" @click="goLogin">登录</van-button>
    </div>
  </div>
</template>

<script>
import { getStorage } from "../utils/storage";
import { mapActions, mapState, mapMutations } from "vuex";
export default {
  name: "bd",
  layout: "layoutMain",
  data() {
    return {
      loading: false,
      finished: false,
      refreshing: false,
      value: "",
      readArr: []
    };
  },
  beforeRouteLeave(to, form, next) {
    if (this.id) {
      let pos = this.$refs.content.scrollTop;
      this.setCurrentPage(pos);
    }
    next();
  },
  methods: {
    ...mapMutations("msbd", ["setCurrentPage"]),
    ...mapActions("msbd", ["getList", "clearFn"]),
    //登录
    goLogin() {
      this.$router.push("/login");
    },
    //跳转搜索
    toSearch() {
      this.$router.push("/search");
    },
    async onLoad() {
      if (this.refreshing) {
        this.clearFn();
        this.refreshing = false;
      }
      await this.getList();
      this.loading = false;
      if (this.list.length == this.total) {
        this.finished = true;
      }
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加q载状态
      this.loading = true;
      this.onLoad();
    }
  },
  computed: {
    ...mapState("msbd", ["list", "total", "currentPage"]),
    id() {
      return this.$store.state.user.id;
    }
  },
  mounted() {
    this.readArr = getStorage();
    if (this.id) {
      this.$refs.content.scrollTop = this.currentPage;
    }
  }
};
</script>

<style lang="scss" scoped>
.van_bar {
  position: fixed;
  top: 0;
  width: 100%;
}
.read > .van-cell__title {
  color: #ccc;
}
.content {
  position: absolute;
  top: 100px;
  bottom: 50px;
  overflow-y: auto;
  width: 100%;
}
</style>